const browserPath = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
const user = "";
const pwd = "";
const testUrl = "rest/me";
const loginUrl = "authui/login.html";
const dasUrl = "das";
const urllib = require('urllib');
const puppeteer = require('puppeteer-core');
const options = {
  executablePath: browserPath,
  ignoreHTTPSErrors: true,
  headless: true,
  defaultViewport: {
    width: 1200,
    height: 600
  }
}
puppeteer.launch(options).then( async browser => {
const page = await browser.newPage();
await page.goto(loginUrl);

const input = await page.waitForSelector('#personalAccountInputId input[type=text]');
await input.type(user);
const pwdDom = await page.waitForSelector('#personalPasswordInputId input[type=password]');
await pwdDom.type(pwd);
await pwdDom.press('Enter');

await page.waitForNavigation({
  waitUntil: 'networkidle2'
});

await page.goto(dasUrl);

await page.waitForNavigation({
  'waitUntil': 'networkidle2'
})

const coo = await page.cookies();

const {authCookies, cookieStr, authObj} = parseCookie(coo);
console.log(cookieStr);

const ret = await urllib.curl(testUrl,{
  method: 'GET',
  dataType: 'json',
  headers: {
    ...authObj,
    cookie: cookieStr
  },
  
});
console.log(ret)
})

function parseCookie(cookies) {
  const authKeys = ['J_SESSION_ID', 'SID', 'businessKey', 'agencyID', 'cftk', 'SessionID'];
  let cookieStr = '';
  const authCookies = cookies.filter(rec => {
    const t = authKeys.find(key => {
      const reg = new RegExp(`${key}$`);
      return reg.test(rec.name);
    })
    const bool = !!t;
    bool && (cookieStr += `${rec.name}=${rec.value};`);
    return bool;
  })

  const authObj = {};
  authCookies.forEach(rec => {
    authObj[rec.name] = rec.value;
  })
  return {authCookies, cookieStr, authObj};
}